package com.quanyan.stadium.service.gameSign.impl;

import com.alibaba.rocketmq.common.message.MessageExt;
import com.google.common.base.Optional;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.quanyan.api.APIRequest;
import com.quanyan.api.APIResponse;
import com.quanyan.api.enums.ApiResponseEnum;
import com.quanyan.assets.request.ReqRuleDetail;
import com.quanyan.assets.response.RespRuleDetail;
import com.quanyan.assets.service.UserAssetsService;
import com.quanyan.club.entity.*;
import com.quanyan.club.service.ClubOpenService;
import com.quanyan.common.Plugin.Page;
import com.quanyan.common.Plugin.PageObj;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.utils.CommonUtils;
import com.quanyan.orderpay.request.*;
import com.quanyan.orderpay.response.RespPayInfo;
import com.quanyan.orderpay.response.RespPreOrder;
import com.quanyan.orderpay.response.mq.OrderNotifyMsg;
import com.quanyan.orderpay.response.mq.RefundNotifyMsg;
import com.quanyan.orderpay.service.OrderPayService;
import com.quanyan.pay.enums.OrderStatusEnum;
import com.quanyan.pay.enums.PayWayEnum;
import com.quanyan.pay.enums.RefundStatusEnum;
import com.quanyan.sms.service.SmsService;
import com.quanyan.stadium.api.req.*;
import com.quanyan.stadium.api.resp.*;
import com.quanyan.stadium.biz.BizGameOrderDao;
import com.quanyan.stadium.biz.BizGameSystemDao;
import com.quanyan.stadium.constants.GameConstants;
import com.quanyan.stadium.entity.*;
import com.quanyan.stadium.entity.vo.*;
import com.quanyan.stadium.enums.GameSystemConfigEnum;
import com.quanyan.stadium.enums.GameTypeConfigEnum;
import com.quanyan.stadium.enums.PayTypeEnum;
import com.quanyan.stadium.enums.errorEnum.GameSignUpEnum;
import com.quanyan.stadium.mapper.*;
import com.quanyan.stadium.service.StadiumSmsService;
import com.quanyan.stadium.service.commonComponent.BaseService;
import com.quanyan.stadium.service.commonComponent.GameMsgPush;
import com.quanyan.stadium.service.commonComponent.OfficialGameCache;
import com.quanyan.stadium.service.gameRules.impl.GameRulePkServiceImpl;
import com.quanyan.stadium.service.gameSign.GameSignUpService;
import com.quanyan.stadium.transfer.GameConfigTransfer;
import com.quanyan.user.response.RespUserInfoBase;
import com.quanyan.user.response.RespUserInfoDetail;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: zyq
 * Date: 2016/6/27 0027
 * Time: 15:32
 */
@Service("gameSignUpService")
public class GameSignUpServiceImpl implements GameSignUpService {

    private static Logger logger = LoggerFactory.getLogger(GameSignUpServiceImpl.class);

    private static final Gson gson = new Gson();

    @Autowired
    ClubOpenService clubOperService;

    @Autowired
    TbGameEventMapper gameEventMapper;

    @Autowired
    private OrderPayService orderPayService;

    @Autowired
    private UserAssetsService userAssetsService;

    @Autowired
    BizGameSystemDao gameSystemDao;

    @Autowired
    TbGameOrderMapper gameOrderMapper;

    @Autowired
    BizGameOrderDao gameOrderDao;

    @Autowired
    BaseService baseService;

    @Autowired
    TbGameEventTeamMapper gameEventTeamMapper;

    @Autowired
    TbUserGameScheduleMapper userGameScheduleMapper;

    @Autowired
    SmsService smsService;

    @Autowired
    GameMsgPush msgPush;

    @Value("${stadium.pay.url}")
    private String payUrl;

    @Value("${stadium.payExpire.url}")
    private String expireUrl;

    @Value("${stadium.refund.url}")
    private String refundUrl;

    @Autowired
    ClubOpenService clubOpenService;

    @Autowired
    TbPointsMapper pointsMapper;

    @Autowired
    TbUserScoreCollectMapper userScoreCollectMapper;

    @Autowired
    BizGameOrderDao bizGameOrderDao;

    @Autowired
    GameRulePkServiceImpl gameRulePkService;

    @Autowired
    TbGameHelpSignMapper gameHelpSignMapper;

    @Autowired
    TbUserSignCountMapper userSignCountMapper;

    @Autowired
    private GameConfigTransfer gameEventTransfer;

    @Autowired
    private StadiumSmsService stadiumSmsService;

    @Autowired
    private OfficialGameCache officialGameCache;


    @Override
    public APIResponse sendSMS(Integer uid) {
        RespUserInfoBase user = baseService.queryUserMsg(uid);
        String number = user.getMobile();
        logger.info("用户发送手机验证码，uid={},手机号码={}", uid, number);
        APIResponse  apiResponse = stadiumSmsService.sendSms(number);
        return apiResponse;
    }

    private boolean verifyValidCode(Integer uid, String code) {
        RespUserInfoBase user = baseService.queryUserMsg(uid);
        String number = user.getMobile();
        logger.info("用户发送手机验证码，uid={},手机号码={}", uid, number);
        APIResponse apiResponse = stadiumSmsService.checkCode(code,number);
        if(apiResponse.getErrcode() == 200){
            return true;
        }else{
            return false;
        }

    }


    @Override
    public APIResponse<TbGameOrder> queryUserOrder(ReqUserOrder request) {
        logger.info("查询用户的订单uid={},订单号={}", request.getUid(), request.getOrderNO());
        TbGameOrderExample example = new TbGameOrderExample();
        TbGameOrderExample.Criteria criteria = example.createCriteria();
        //criteria.andUidEqualTo(request.getUid());
        criteria.andTradeOrderNoEqualTo(request.getOrderNO());
        List<TbGameOrder> list = gameOrderMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(list)) {
            TbGameOrder tbGameOrder = list.get(0);
            logger.info("查询用户的订单成功,订单详情：{}", gson.toJson(tbGameOrder));
            return APIResponse.returnSuccess(tbGameOrder);
        } else {
            logger.info("查询用户的订单详情为空！");
            return APIResponse.returnFail("查询订单详情为空！");
        }
    }

    //是否能报名：1：用户属于俱乐部，2：用户是俱乐部管理员
    @Override
    public APIResponse<?> getSignClub(ReqUserSignUp request) {
        TbGameEvent tbGameEvent = gameEventMapper.selectByPrimaryKey(request.getGameId());
        if (null == tbGameEvent) {
            logger.info("用户uid={}，以俱乐部id={}开始报名活动gameid={}报名失败，原因：{}", request.getUid(), request.getClubId(), request.getGameId(), GameSignUpEnum.HAVING_NOT_GAME_FROM_GAMEID.getLabel());
            return APIResponse.returnFail(GameSignUpEnum.HAVING_NOT_GAME_FROM_GAMEID.getId(), GameSignUpEnum.HAVING_NOT_GAME_FROM_GAMEID.getName());
        }
        if(request.getIsHelpSign() == 0) {
            if (new Date().after(tbGameEvent.getEndTime())) {
                logger.info("用户uid={}，以俱乐部id={}开始报名活动gameid={}报名失败，原因：{}", request.getUid(), request.getClubId(), request.getGameId(), GameSignUpEnum.GAME_IS_END_STOP_SIGN.getLabel());
                return APIResponse.returnFail(GameSignUpEnum.GAME_IS_END_STOP_SIGN.getId(), GameSignUpEnum.GAME_IS_END_STOP_SIGN.getName());
            }
            if (new Date().after(tbGameEvent.getSignEndTime())) {
                logger.info("用户uid={}，以俱乐部id={}开始报名活动gameid={}报名失败，原因：{}", request.getUid(), request.getClubId(), request.getGameId(), GameSignUpEnum.GAME_SIGN_IS_SOPT.getLabel());
                return APIResponse.returnFail(GameSignUpEnum.GAME_SIGN_IS_SOPT.getId(), GameSignUpEnum.GAME_SIGN_IS_SOPT.getName());
            }
        }
        if (tbGameEvent.getInventoryLevel() <= 0) {
            logger.info("用户uid={}，以俱乐部id={}开始报名活动gameid={}报名失败，原因：{}", request.getUid(), request.getClubId(), request.getGameId(), GameSignUpEnum.GAME_SIGN_USER_IS_FULL.getLabel());
            return APIResponse.returnFail(GameSignUpEnum.GAME_SIGN_USER_IS_FULL.getId(), GameSignUpEnum.GAME_SIGN_USER_IS_FULL.getName());
        }
        if (tbGameEvent.getIsVisible() == 0) {
            //俱乐部内部可见
            logger.info("用户uid={}，以俱乐部id={}开始报名活动gameid={}报名失败，原因：{}", request.getUid(), request.getClubId(), request.getGameId(), GameSignUpEnum.NOT_IN_CLUB.getLabel());
            Integer clubId = tbGameEvent.getClubId();
            RespIsClubMember respIsClubMember = clubOperService.isClubMember(clubId, request.getUid());
            if (!respIsClubMember.isFlag()) {
                return APIResponse.returnFail(GameSignUpEnum.NOT_IN_CLUB.getId(), GameSignUpEnum.NOT_IN_CLUB.getName());
            }
        }
        logger.info("查询用户uid={}所在的俱乐部列表", request.getUid());
        List<ClubInfo> clubInfos = Lists.newArrayList();
        List<RespClubOpenInfo> clubList = clubOperService.getUserClubInfoList(request.getUid());
        logger.info("查询到的俱乐部列表：{}", gson.toJson(clubList));

        if (CollectionUtils.isEmpty(clubList)) {
            logger.info("查询用户所在的俱乐部列表为空！");
            return APIResponse.returnSuccess(clubInfos);
        } else {
            for (RespClubOpenInfo clubOpenInfo : clubList) {
                if (Optional.fromNullable(clubOpenInfo).isPresent()) {
                    if (!tbGameEvent.getCategoryId().equals(Integer.parseInt(clubOpenInfo.getClubType())))
                        continue;
                    ClubInfo clubInfo = new ClubInfo();
                    logger.info("查询用户uid={}是否是俱乐部id={}的管理员", request.getUid(), clubOpenInfo.getClubId());
                    RespIsClubMember respIsClubMember = clubOperService.isClubMember(clubOpenInfo.getClubId(), request.getUid());
                    BeanUtils.copyProperties(clubOpenInfo, clubInfo);
                    if (respIsClubMember.isFlag()) {
                        if (respIsClubMember.getRoleCode().equals(Constants.ClubRole.CLUB_ROLE_PRESIDENT) || respIsClubMember.getRoleCode().equals(Constants.ClubRole.ROLE_CLUB_ADMIN)) {
                            logger.info("用户uid={}是俱乐部clubId={}的管理员！", request.getUid(), clubInfo.getClubId());
                            clubInfo.setIsAdmin(1);
                        } else {
                            logger.info("用户uid={}不是俱乐部clubId={}的管理员！", request.getUid(), clubInfo.getClubId());
                            clubInfo.setIsAdmin(0);
                        }
                        clubInfo.setRoleCode(respIsClubMember.getRoleCode());
                    }

                    //查询当前用户是否属于该俱乐部成员
                    Boolean flag = false;
                    try {
                        List<RespClubMemberBaseInfo> list = clubOperService.getClubMembers(clubOpenInfo.getClubId(), true);
                        if (list != null && list.size() > 0) {
                            flag = true;
                        }
                    } catch (Exception e) {
                        logger.error("查询用户所在俱乐部代表队信息失败！");
                    }
                    clubInfo.setHasTeam(flag ? 1 : 0);
                    clubInfos.add(clubInfo);
                }
            }
            return APIResponse.returnSuccess(clubInfos);
        }
    }


    /**
     * 调用支付中心，封装鸟蛋信息
     * @param uid
     * @param price
     * @param signCount
     * @return
     */
    public OtherPayWay eggPay(Integer uid, BigDecimal price,int signCount) {
        logger.info("查询用户的鸟蛋相关信息，uid={},比赛抵扣总金额={}", uid, price);
        ReqRuleDetail reqRuleDetail = new ReqRuleDetail();
        reqRuleDetail.setUid(uid);
        reqRuleDetail.setSystemCode(Constants.STADIUM_SYSTEM_CODE);
        reqRuleDetail.setBusinessCode(Constants.STADIUM_GAME_SIGN_BUSINESS_CODE);
        reqRuleDetail.setOrderAmount(price.multiply(new BigDecimal(signCount)));
        APIRequest<ReqRuleDetail> apiRequest = new APIRequest<ReqRuleDetail>();
        apiRequest.setData(reqRuleDetail);
        APIResponse<List<RespRuleDetail>> response = userAssetsService.getUserAccumulateAndRule(apiRequest);
        logger.info("查询用户的鸟蛋相关信息，uid={},调用dubbo，响应内容：{}", uid, new Gson().toJson(response));
        OtherPayWay otherPayWay = new OtherPayWay();
        otherPayWay.setOtherPayType(GameConstants.OTHER_PAY_EGG);
        if (response != null && response.getData() != null && response.getData().size() > 0) {
            RespRuleDetail respRuleDetail = response.getData().get(0);
            BigDecimal toRmb = respRuleDetail.getExchangeRMB();
            if (toRmb.compareTo(price) >= 0) {
                otherPayWay.setToRMB(price.doubleValue());
                otherPayWay.setUseAmount(price.multiply(BigDecimal.valueOf(10D)).doubleValue());
            } else {
                otherPayWay.setToRMB(toRmb.doubleValue());
                otherPayWay.setUseAmount(toRmb.multiply(BigDecimal.valueOf(10D)).doubleValue());
            }
            otherPayWay.setName("鸟蛋抵扣");
            otherPayWay.setDesc("-￥" + otherPayWay.getToRMB() + " （消耗" + otherPayWay.getUseAmount().intValue() + "鸟蛋）");
            otherPayWay.setEnable(true);
            otherPayWay.setRate(Double.parseDouble(respRuleDetail.getAccumulateRule()));
            return otherPayWay;
        } else {
            otherPayWay.setEnable(false);
        }
        return otherPayWay;
    }

    public OtherPayWay getClubPay(Integer uid, Integer clubId) {
        logger.info("查询用户uid={}所在的俱乐部clubid={}的余额{}", uid, clubId);
        OtherPayWay otherPayWay = new OtherPayWay();
        otherPayWay.setOtherPayType(GameConstants.OTHER_PAY_CLUB);
        RespClubMemberFund respClubMemberFund = clubOperService.getClubMemberFund(uid, clubId);
        logger.info("查询用户uid={}所在的俱乐部clubid={}的余额{},调用dubbo响应内容：{}", uid, clubId, new Gson().toJson(respClubMemberFund));
        if (Optional.fromNullable(respClubMemberFund).isPresent() && Optional.fromNullable(respClubMemberFund.getOnlineFund()).isPresent()) {
            otherPayWay.setTotalAmount(respClubMemberFund.getOnlineFund().doubleValue());
        } else {
            otherPayWay.setTotalAmount(0d);
        }
        otherPayWay.setRate(1d);
        otherPayWay.setToRMB(otherPayWay.getTotalAmount() * otherPayWay.getRate());
        otherPayWay.setName("俱乐部余额抵扣");
        otherPayWay.setEnable(true);
        return otherPayWay;
    }

    /**
     * 包装GameEvent对象
     */
    public void wrapTBgameEvent(TbGameEvent tbGameEvent, GamePlaceOrder gamePlaceOrder) {
        List<Integer> integers = Lists.newArrayList();
        integers.add(tbGameEvent.getPlaceId());
        Map<Integer, PlaceInfo> map = baseService.queryPlaceInfoMsgList(integers);
        BeanUtils.copyProperties(tbGameEvent, gamePlaceOrder);
        if (tbGameEvent.getPayType() > 0) {
            gamePlaceOrder.setPrice(new BigDecimal(0.00));
        }
        if (!MapUtils.isEmpty(map)) {
            PlaceInfo placeInfo = map.get(tbGameEvent.getPlaceId());
            logger.info("查询到该比赛gameid={}所在的场馆id={},场馆名称={}", tbGameEvent.getId(), placeInfo.getPlaceId(), placeInfo.getName());
            gamePlaceOrder.setPlaceName(placeInfo.getName());
        }
    }



    //支付以个人形式支付，支持的支付方式：鸟蛋，俱乐部余额，金额
    @Override
    public APIResponse<?> userSign(ReqUserSignUp request) {
        logger.info("用户uid={}，开始报名活动gameid={}", request.getUid(), request.getGameId());
        TbGameEvent tbGameEvent = gameEventMapper.selectByPrimaryKey(request.getGameId());
        if (null == tbGameEvent || tbGameEvent.getId() < 1) {
            logger.info("用户uid={}，以俱乐部id={}开始报名活动gameid={}报名失败，原因：{}", request.getUid(), request.getClubId(), request.getGameId(), GameSignUpEnum.HAVING_NOT_GAME_FROM_GAMEID.getLabel());
            return APIResponse.returnFail(GameSignUpEnum.HAVING_NOT_GAME_FROM_GAMEID.getId(), GameSignUpEnum.HAVING_NOT_GAME_FROM_GAMEID.getName());
        }
        RespUserSignUp userSignUp = new RespUserSignUp();
        if(request.getIsHelpSign() == 1){
            //走代报名逻辑

            TbGameEventTeamExample teamExample = new TbGameEventTeamExample();
            TbGameEventTeamExample.Criteria criteria = teamExample.createCriteria();
            criteria.andUidIn(request.getUids());
            criteria.andGameEventIdEqualTo(request.getGameId());
            criteria.andIsDeleteEqualTo(GameConstants.IS_NOT_DELETE);
            List<TbGameEventTeam> tbGameEventTeams = gameEventTeamMapper.selectByExample(teamExample);
            if(tbGameEventTeams.size() > 0){
                String errorMsg = "";
                int count = 0;
                for(TbGameEventTeam tbGameEventTeam : tbGameEventTeams){
                    count ++;
                    if(count == 3){
                        break;
                    }
                    RespUserInfoDetail respUserInfoDetail = baseService.queryUserMsg(tbGameEventTeam.getUid());
                    errorMsg = errorMsg + respUserInfoDetail.getNickName() + ",";
                }
                errorMsg = count == 3 ? errorMsg.substring(0,errorMsg.length() -1)+"等" : errorMsg.substring(0,errorMsg.length() -1);
                return APIResponse.returnFail(errorMsg + "用户已自主报名，请勿重复报名哦");
            }
            if(tbGameEvent.getInventoryLevel() - request.getUids().size() < 0){
                String message = "有其他用户报名咯，当前可报名名额为"+tbGameEvent.getInventoryLevel() + "人";
                return APIResponse.returnFail(GameSignUpEnum.GAME_SIGN_USER_IS_FULL.getId(), message);
            }
        }
        if (tbGameEvent.getGameTeamType() == 1) {
            //以俱乐部参加
            if (request.getClubId() == null) {
                return APIResponse.returnFail(GameSignUpEnum.HAVE_NO_CLUB.getId(), GameSignUpEnum.HAVE_NO_CLUB.getName());
            }
            //这里加个判断，判断是否已经报过名
            TbGameEventTeamExample gameEventTeamExample = new TbGameEventTeamExample();
            TbGameEventTeamExample.Criteria criteria = gameEventTeamExample.createCriteria();
            criteria.andClubIdEqualTo(request.getClubId());
            criteria.andGameEventIdEqualTo(request.getGameId());
            criteria.andIsDeleteEqualTo(GameConstants.IS_NOT_DELETE);
            List<TbGameEventTeam> teams = gameEventTeamMapper.selectByExample(gameEventTeamExample);
            if (teams != null && teams.size() >= 1) {
                return APIResponse.returnFail(GameSignUpEnum.CLUB_HAS_SIGN.getId(), GameSignUpEnum.CLUB_HAS_SIGN.getName());
            }
        }
        if(request.getIsHelpSign() == 0) {
            if (new Date().after(tbGameEvent.getEndTime())) {
                logger.info("用户uid={}，以俱乐部id={}开始报名活动gameid={}报名失败，原因：{}", request.getUid(), request.getClubId(), request.getGameId(), GameSignUpEnum.GAME_IS_END_STOP_SIGN.getLabel());
                return APIResponse.returnFail(GameSignUpEnum.GAME_IS_END_STOP_SIGN.getId(), GameSignUpEnum.GAME_IS_END_STOP_SIGN.getName());
            }
            if (new Date().after(tbGameEvent.getSignEndTime())) {
                logger.info("用户uid={}，以俱乐部id={}开始报名活动gameid={}报名失败，原因：{}", request.getUid(), request.getClubId(), request.getGameId(), GameSignUpEnum.GAME_SIGN_IS_SOPT.getLabel());
                return APIResponse.returnFail(GameSignUpEnum.GAME_SIGN_IS_SOPT.getId(), GameSignUpEnum.GAME_SIGN_IS_SOPT.getName());
            }
        }
        if (tbGameEvent.getInventoryLevel() <= 0) {
            logger.info("用户uid={}，以俱乐部id={}开始报名活动gameid={}报名失败，原因：{}", request.getUid(), request.getClubId(), request.getGameId(), GameSignUpEnum.GAME_SIGN_USER_IS_FULL.getLabel());
            return APIResponse.returnFail(GameSignUpEnum.GAME_SIGN_USER_IS_FULL.getId(), GameSignUpEnum.GAME_SIGN_USER_IS_FULL.getName());
        }
        if(request.getIsHelpSign() != 1) {
            GameSignUpEnum gameSignUpEnum = confirmSign(tbGameEvent, request.getUid(), request.getClubId());
            if (gameSignUpEnum.getId() != GameSignUpEnum.GAME_SING_OK.getId()) {
                logger.info("用户uid={}，以俱乐部id={}开始报名活动gameid={}报名失败，原因：{}", request.getUid(), request.getClubId(), request.getGameId(), GameSignUpEnum.USER_HAVING_NO_SIGN_ACCESS.getLabel());
                return APIResponse.returnFail(gameSignUpEnum.getId(), gameSignUpEnum.getName());
            }
        }
        GamePlaceOrder gamePlaceOrder = new GamePlaceOrder();
        wrapTBgameEvent(tbGameEvent, gamePlaceOrder);
        userSignUp.setGameEvent(gamePlaceOrder);
        if (request.getUserCount() != null && request.getUserCount() > 0) {
            gamePlaceOrder.setPrice(gamePlaceOrder.getPrice().multiply(BigDecimal.valueOf(request.getUserCount())));
        }
        //查询支持的支付方式
        List<RespPayInfo> payInfos = baseService.queryPayTypeList();
        if (!CollectionUtils.isEmpty(payInfos)) {
            userSignUp.setPayInfos(payInfos);
        }
        //线上还是线下支付
        userSignUp.setPayTypeModel(gameEventTransfer.getPayTypeModelById(tbGameEvent.getPayType().intValue()));
        List<OtherPayWay> list = Lists.newArrayList();
        //其他支付方式、俱乐部支付（不用），鸟蛋
        if (tbGameEvent.getPayType().intValue() == PayTypeEnum.CONFIG_PAY_TYPE_ONLINE.getId()) {
            OtherPayWay otherPayWay = eggPay(request.getUid(), gamePlaceOrder.getPrice(),request.getUserCount() == null ? 1 : request.getUserCount());
            list.add(otherPayWay);
        }
        userSignUp.setOtherPayWays(list);

        //报名人数更新
        officialGameCache.delGameEvent(request.getGameId());
        return APIResponse.returnSuccess(userSignUp);
    }


    public int insertNewTeam(TbGameEvent gameEvent, Integer uid, Integer clubId, String orderNO,Boolean flag) {
        int result = 0;
        logger.info("更新报名信息：gameid={},uid={},clubid={}", gameEvent.getId(), uid, clubId);
        if (gameEvent.getType() == 0
                && gameEvent.getGameEventType() != GameTypeConfigEnum.CONFIG_GAME_EVENT_TYPE_NGKC.getId()) {
            logger.info("该比赛属于官方比赛，且比赛类型不是积分赛，更新报名状态！");
            TbGameEventTeamExample eventTeamExample = new TbGameEventTeamExample();
            TbGameEventTeamExample.Criteria criteria1 = eventTeamExample.createCriteria();
            criteria1.andGameEventIdEqualTo(gameEvent.getId());
            if (gameEvent.getGameTeamType() == 0) {
                criteria1.andUidEqualTo(uid);
            } else {
                criteria1.andClubIdEqualTo(clubId);
            }
            criteria1.andIsForfeitEqualTo((byte) 0);
            criteria1.andIsJoinAccessEqualTo((byte) 1);
            criteria1.andIsDeleteEqualTo((byte) 1);
            TbGameEventTeam tbGameEventTeam = new TbGameEventTeam();
            tbGameEventTeam.setIsDelete((byte) 0);
            gameEventTeamMapper.updateByExampleSelective(tbGameEventTeam, eventTeamExample);
            result = tbGameEventTeam.getId();
        } else {
            double score = 0;
            if (gameEvent.getGameTeamType() == 0) {
                TbPointsExample example = new TbPointsExample();
                TbPointsExample.Criteria criteria = example.createCriteria();
                criteria.andUidEqualTo(uid);
                criteria.andCategoryIdEqualTo(gameEvent.getCategoryId().intValue());
                //criteria.andIsDeleteEqualTo(GameConstants.IS_NOT_DELETE);
                List<TbPoints> tbPointses = pointsMapper.selectByExample(example);
                if (!CollectionUtils.isEmpty(tbPointses)) {
                    TbPoints points = tbPointses.get(0);
                    score = points.getScore();
                }
            } else {
                /*RespClubPlainInfo clubPlainInfo = baseService.queryClubMsg(clubId);
                if(clubPlainInfo != null) {
                    score = clubPlainInfo.getIntegral();
                }*/
            }
            logger.info("直接插入队伍信息！");
            TbGameEventTeam tbGameEventTeam = new TbGameEventTeam();
            tbGameEventTeam.setGameEventId(gameEvent.getId());
            tbGameEventTeam.setType(gameEvent.getGameTeamType());

            tbGameEventTeam.setScore(score);
            if (gameEvent.getGameTeamType() == 0) {
                tbGameEventTeam.setUid(uid);
            } else if (gameEvent.getGameTeamType() == 1) {
                tbGameEventTeam.setClubId(clubId);
            }
            tbGameEventTeam.setSignUid(uid);
            tbGameEventTeam.setIsForfeit((byte) 0);
            tbGameEventTeam.setIsJoinAccess((byte) 1);
            tbGameEventTeam.setIsDelete((byte) 0);
            gameEventTeamMapper.insertSelective(tbGameEventTeam);
            result = tbGameEventTeam.getId();
            if (gameEvent.getType() == 2 && gameEvent.getGameSystemType() == 6) {
                List<Integer> list = Lists.newArrayList();
                list.add(result);
                try {
                    gameRulePkService.updateGameSchedule(gameEvent.getId(), list);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            //这里插入代表对
            if (gameEvent.getGameTeamType() == 1 && clubId != null) {
                //查询俱乐部代表队列表
                Map<Integer, List<Integer>> map = null;
                List<Integer> clubs = Lists.newArrayList();
                clubs.add(clubId);
                try {
                    map = clubOperService.getClubsTeamMembersId(clubs);
                } catch (Exception e) {
                    logger.error("更新队伍信息，查询俱乐部代表队异常:{}", e);
                }
                if (map != null) {
                    List<Integer> users = map.get(clubId);
                    if (users != null && users.size() > 0) {
                        gameSystemDao.initTbGameClubTeamUser(gameEvent.getId(), clubId, users, tbGameEventTeam.getId());
                    }
                }

            }


        }

        try {
            //消息推送
            List<Integer> uids = new ArrayList<Integer>();
            uids.add(uid);
            if(gameEvent.getGameSystemType().intValue() == GameSystemConfigEnum.CONFIG_GAME_TYPE_PK.getId()) {
                if(flag) {
                    msgPush.newSignUser(gameEvent);
                }
            }
            if(flag) {
                msgPush.pushGameSignSuccess(uids, gameEvent);
            }
        } catch (Exception e) {
            logger.info("用户uid={},clubid={}报名gameid={}成功，发送报名消息失败！", uid, clubId, gameEvent.getId());
        }
        return result;
    }


    public void insertDoubleTeam(TbGameEvent gameEvent, List<Integer> uids, String orderNO) {
        logger.info("双打比赛插入捆绑用户");
        List<Integer> eventTeamIds = new ArrayList<>();
        for (Integer temp : uids) {
            TbGameEventTeam tbGameEventTeam = new TbGameEventTeam();
            tbGameEventTeam.setGameEventId(gameEvent.getId());
            tbGameEventTeam.setType(gameEvent.getGameTeamType());
            tbGameEventTeam.setScore(0.0);
            tbGameEventTeam.setUid(temp);
            tbGameEventTeam.setIsForfeit((byte) 0);
            tbGameEventTeam.setIsJoinAccess((byte) 1);
            tbGameEventTeam.setIsDelete((byte) 0);
            gameEventTeamMapper.insertSelective(tbGameEventTeam);
            eventTeamIds.add(tbGameEventTeam.getId());
        }
        if (eventTeamIds.size() >2) {
            return;
        }
        try {
            //消息推送
            msgPush.pushGameSignSuccess(uids,gameEvent);
        } catch (Exception e) {
            Gson gson = new Gson();
            logger.info("双打用户uid={},报名gameid={}成功，发送报名消息失败！", gson.toJson(uids), gameEvent.getId());
        }
        logger.info("双打比赛插入捆绑用户成功,用户列表大小:{}, 队伍列表大小:{}", uids.size(), eventTeamIds.size());
        bizGameOrderDao.insertTbTeamDoubleAddendum(gameEvent.getId(), eventTeamIds);
    }


    public Map<Integer, Integer> insertDoubleTeamWithTeam(TbGameEvent gameEvent, List<Integer> uids, String orderNO,boolean flag) {
        logger.info("双打比赛插入捆绑用户");
        Map<Integer, Integer> result = new HashMap<>();
        List<Integer> eventTeamIds = new ArrayList<>();
        for (Integer temp : uids) {
            TbGameEventTeam tbGameEventTeam = new TbGameEventTeam();
            tbGameEventTeam.setGameEventId(gameEvent.getId());
            tbGameEventTeam.setType(gameEvent.getGameTeamType());
            tbGameEventTeam.setScore(0.0);
            tbGameEventTeam.setUid(temp);
            tbGameEventTeam.setIsForfeit((byte) 0);
            tbGameEventTeam.setIsJoinAccess((byte) 1);
            tbGameEventTeam.setIsDelete((byte) 0);
            int teamResult = gameEventTeamMapper.insertSelective(tbGameEventTeam);
            result.put(temp,tbGameEventTeam.getId());
            eventTeamIds.add(tbGameEventTeam.getId());
            if(flag) {
                if (gameEvent.getType() == 2 && gameEvent.getGameSystemType() == 6) {
                    List<Integer> list = Lists.newArrayList();
                    list.add(tbGameEventTeam.getId());
                    try {
                        gameRulePkService.updateGameSchedule(gameEvent.getId(), list);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }}

        logger.info("双打比赛插入捆绑用户成功,用户列表大小:{}, 队伍列表大小:{}", uids.size(), eventTeamIds.size());
        bizGameOrderDao.insertTbTeamDoubleAddendum(gameEvent.getId(), eventTeamIds);
        try {
            //消息推送
            if(flag) {
                msgPush.pushGameSignSuccess(uids, gameEvent);
            }
            if(gameEvent.getGameSystemType().intValue() == GameSystemConfigEnum.CONFIG_GAME_TYPE_PK.getId()) {
                if(flag) {
                    msgPush.newSignUser(gameEvent);
                }
            }
        } catch (Exception e) {
            Gson gson = new Gson();
            logger.info("双打用户uid={},报名gameid={}成功，发送报名消息失败！", gson.toJson(uids), gameEvent.getId());
        }
        return result;
    }

    /**
     * 判断用户是否有资格报名参加该比赛
     * <p>
     * 大球,校验当前用户是否是俱乐部管理员;俱乐部是否创建代表队
     * 小球校验是否已经报名;
     * 小球如果是对内的话,是否当前俱乐部成员
     *
     * @param gameEvent
     * @param uid
     * @return
     */
    protected GameSignUpEnum confirmSign(TbGameEvent gameEvent, Integer uid, Integer clubId) {
        logger.info("验证用户uid={},以俱乐部id={}报名活动id={},是否有报名权限", uid, clubId, gameEvent.getId());
        TbGameEventTeamExample example = new TbGameEventTeamExample();
        TbGameEventTeamExample.Criteria criteria = example.createCriteria();
        criteria.andGameEventIdEqualTo(gameEvent.getId());
        criteria.andIsDeleteEqualTo(GameConstants.IS_NOT_DELETE);
        if (gameEvent.getGameEventType().intValue() == GameConstants.IS_DELETE.intValue()) {    //俱乐部报名
            //TODO 等待石桌 接口
            if (true) { //校验用户是否是该俱乐部管理元

            }
            criteria.andClubIdEqualTo(clubId);
        } else {  //个人单位报名
            if (gameEvent.getIsVisible() == GameConstants.IS_NOT_DELETE) {  //对内逻辑
                if (!baseService.isJoinedClub(clubId, uid)) {
                    logger.info("用户uid={}未加入俱乐部clubId={}，没有权限报名队内比赛", uid, clubId);
                    return GameSignUpEnum.NOT_IN_CLUB;
                }
            }
            criteria.andUidEqualTo(uid);
        }
        List<TbGameEventTeam> teams = gameEventTeamMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(teams)) {
            //说明用户已经报名过这个活动，不能重复报名
            logger.info("用户uid={}已经报名过这个活动gameid={}，不能重复报名", uid, gameEvent.getId());
            return GameSignUpEnum.USER_HAVING_NO_SIGN_ACCESS;
        }
        return GameSignUpEnum.GAME_SING_OK;
    }

    /**
     * 拿到用户一天中失败的订单数量
     *
     * @param uid
     * @return
     */
    protected Integer checkUsersFailOrder(Integer uid) {
        logger.info("查询用户再一天中支付失败的订单数量uid={}", uid);
        TbGameOrderExample example = new TbGameOrderExample();
        TbGameOrderExample.Criteria criteria = example.createCriteria();
        criteria.andPayWaitEqualTo(GameConstants.FAIL_PAY);
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.HOUR, -24);
        criteria.andCreateTimeGreaterThanOrEqualTo(calendar.getTime());
        criteria.andUidEqualTo(uid);
        List<TbGameOrder> gameOrders = gameOrderMapper.selectByExample(example);
        Integer count = CollectionUtils.isEmpty(gameOrders) ? 0 : gameOrders.size();
        logger.info("该用户uid={}失败的订单数量为:{}", uid, count);
        return count;
    }

    /**
     * 不走支付系统，直接下单，有两种情况（因为支付系统只支持鸟蛋和金额支付，不支持俱乐部余额支付，坑！）：
     * 1.活动免费，直接下单
     * 2.活动不免费，使用俱乐部余额下单
     */
    protected int directOrder(Integer clubId, GamePlaceOrder gameEvent, Integer uid, double clubAmount, RespPreOrder preOrder,int helpSign,List<Integer> uids) {
        logger.info("用户uid={}，clubid={}没有走金额支付系统，只有俱乐部支付：{}", uid, clubId, clubAmount);
        Date now = new Date();
        TbGameOrder tbGameOrder = new TbGameOrder();
        tbGameOrder.setTradeOrderNo(CommonUtils.generateBusinessOrderNo("FREE_", uid));
        tbGameOrder.setType(gameEvent.getType());
        tbGameOrder.setGameTeamType(gameEvent.getGameTeamType());
        tbGameOrder.setUid(uid);
        tbGameOrder.setClubid(clubId);
        tbGameOrder.setGameEventId(gameEvent.getId());
        tbGameOrder.setOrderAmount(BigDecimal.valueOf(clubAmount));
        tbGameOrder.setPayAmount(BigDecimal.valueOf(0));
        tbGameOrder.setAccumulate(0);
        tbGameOrder.setClubAmount(BigDecimal.valueOf(clubAmount));
        tbGameOrder.setGamePlace(gameEvent.getPlaceName());
        tbGameOrder.setOrderTime(now);
        tbGameOrder.setDeadTime(now);
        tbGameOrder.setPayTime(now);
        tbGameOrder.setPayWait(GameConstants.SUCCESS_PAY);
        tbGameOrder.setOrderStatus(GameConstants.SUCCESS_ORDER);
        tbGameOrder.setIsClose(GameConstants.ORDER_IS_CLOST_YES);
        tbGameOrder.setContractMobile(gameEvent.getManagerMobile());
        tbGameOrder.setContact(gameEvent.getManagerName());
        tbGameOrder.setGameName(gameEvent.getName());
        if(helpSign == 1){
            tbGameOrder.setIsHelpSign((byte) 1);
            tbGameOrder.setHelpSignUids(new Gson().toJson(uids));
        }
        int result = gameOrderMapper.insertSelective(tbGameOrder);
        preOrder.setOutTradeNo(tbGameOrder.getTradeOrderNo());
        return result;
    }


    /**
     * 说明：上一个版本双打报名人数让扣除2，2016年10月12日后让扣1，所以这里改成返回1
     *
     * @param gameEvent
     * @return
     */
    private int signCount(TbGameEvent gameEvent,int isHelpSign,int count) {
        /*if(baseService.getGameCategoryById(gameEvent.getGameCategoryType().intValue()).getMinNum() == 2
                && baseService.getGameCategoryById(gameEvent.getGameCategoryType().intValue()).getMaxNum() == 2){
            return 2;
        }else{
            return 1;
        }*/
        if(isHelpSign == 1){
            return count;
        }
        return 1;

    }

    /**
     * 报名
     *
     * @param request
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public APIResponse gameOrder(ReqPay request , boolean isHelpSign) {
        logger.info("1.用户uid={}开始支付活动：gameid={},金额支付={},鸟蛋支付={}，俱乐部支付={}", request.getUid(), request.getGameId(), request.getPrice(), request.getEggToRMB(), 0);
        //校验验证码
        if (null != request.getCode()) {
            logger.info("2.用户uid={}产生验证码，验证码验证code={}", request.getUid(), request.getCode());
            if (!verifyValidCode(request.getUid(), request.getCode())) {
                logger.info("2.用户uid={}验证码不通过！", request.getUid());
                return APIResponse.returnFail("验证失败！", ApiResponseEnum.VALIDATE_CODE_ERROR);
            }
        }

        //校验活动的有效性
        TbGameEvent tbGameEvent = gameEventMapper.selectByPrimaryKey(request.getGameId());
        if (null == tbGameEvent || null == tbGameEvent.getId() || tbGameEvent.getId() < 1) {
            logger.info("用户uid={},支付比赛gameid={}查询该比赛时该比赛不存在！", request.getUid(), request.getGameId());
            return APIResponse.returnFail(GameSignUpEnum.HAVING_NOT_GAME_FROM_GAMEID.getId(), GameSignUpEnum.HAVING_NOT_GAME_FROM_GAMEID.getName());
        }

        //支付时关闭上一次未支付的订单
        int signCount = signCount(tbGameEvent,request.getIsHelpSign(),request.getUids()==null?1:request.getUids().size());
        GamePlaceOrder gamePlaceOrder = new GamePlaceOrder();
        wrapTBgameEvent(tbGameEvent, gamePlaceOrder);
        TbGameOrderExample gameOrderExample = new TbGameOrderExample();
        TbGameOrderExample.Criteria orderCriteria = gameOrderExample.createCriteria();
        orderCriteria.andPayWaitEqualTo(GameConstants.ON_PAYING);
        orderCriteria.andOrderStatusEqualTo(GameConstants.WAIT_ORDER);
        orderCriteria.andIsCloseEqualTo(GameConstants.ORDER_IS_CLOST_NO);
        orderCriteria.andUidEqualTo(request.getUid());
        orderCriteria.andGameEventIdEqualTo(request.getGameId());
        List<TbGameOrder> orders = gameOrderMapper.selectByExample(gameOrderExample);
        if (!CollectionUtils.isEmpty(orders)) {
            //说明有未支付的订单，返回失败！
            logger.info("用户uid={},支付比赛gameid={}还有未支付的订单，删除上一个订单", request.getUid(), request.getGameId());
            for (TbGameOrder order : orders) {
                TbGameOrder tbGameOrder = new TbGameOrder();
                tbGameOrder.setId(order.getId());
                tbGameOrder.setIsClose(GameConstants.IS_DELETE);
                gameOrderMapper.updateByPrimaryKeySelective(tbGameOrder);
                gameSystemDao.updateGameStorage(request.getGameId(), -signCount);
            }
        }
        if (checkUsersFailOrder(request.getUid()) > GameConstants.FAILED_ORDER_LIMIT) {
            logger.info("用户uid={},支付比赛gameid={}一天内产生了100条失败订单，不能继续下单", request.getUid(), request.getGameId());
            return APIResponse.returnFail(GameSignUpEnum.USER_FAIL_ORDER_LIMIT.getId(), GameSignUpEnum.USER_FAIL_ORDER_LIMIT.getName());
        }
        if(!isHelpSign){
            if (new Date().after(tbGameEvent.getEndTime())) {
                logger.info("用户uid={},支付比赛gameid={}查询该比赛时该比赛已经结束，停止报名！", request.getUid(), request.getGameId());
                return APIResponse.returnFail(GameSignUpEnum.GAME_IS_END_STOP_SIGN.getId(), GameSignUpEnum.GAME_IS_END_STOP_SIGN.getName());
            }
            if (new Date().after(tbGameEvent.getSignEndTime())) {
                logger.info("用户uid={},支付比赛gameid={}查询该比赛时该比赛已经截止报名！", request.getUid(), request.getGameId());
                return APIResponse.returnFail(GameSignUpEnum.GAME_SIGN_IS_SOPT.getId(), GameSignUpEnum.GAME_SIGN_IS_SOPT.getName());
            }
        }

        GameSignUpEnum gameSignUpEnum = null;
        if(request.getIsHelpSign() != 1) {
            gameSignUpEnum = confirmSign(tbGameEvent, request.getUid(), request.getClubId());
            if (gameSignUpEnum.getId() != GameSignUpEnum.GAME_SING_OK.getId()) {
                logger.info("用户uid={},支付比赛gameid={}查询该比赛时发现该用户没有报名权限！", request.getUid(), request.getGameId());
                return APIResponse.returnFail(GameSignUpEnum.USER_HAVING_NO_SIGN_ACCESS.getId(), GameSignUpEnum.USER_HAVING_NO_SIGN_ACCESS.getName());
            }
        }
        if (tbGameEvent.getInventoryLevel() <= 0) {
            logger.info("用户uid={},支付比赛gameid={}查询该比赛时该比赛报名人数已满！", request.getUid(), request.getGameId());
            return APIResponse.returnFail(GameSignUpEnum.GAME_SIGN_USER_IS_FULL.getId(), GameSignUpEnum.GAME_SIGN_USER_IS_FULL.getName());
        }
        //验证码
        if (tbGameEvent.getPayType().intValue() == 0 && (request.getPrice() == null || request.getPrice().equals(0.00) && null == request.getCode())) {
            logger.info("验证0元订单，看是否会产生验证码！");
            if (tbGameEvent.getPrice().doubleValue() >= 1000) {
                logger.info("用户产生0元订单，且报名费大于1000,产生验证码！");
                return APIResponse.returnSuccess(null, ApiResponseEnum.WAIT_SMS_CODE_CONFIRM);
            } else {
                //连续0元订单，2条，产生验证码
                TbGameOrderExample orderExample = new TbGameOrderExample();
                TbGameOrderExample.Criteria criteria1 = orderExample.createCriteria();
                criteria1.andPayWaitEqualTo(GameConstants.SUCCESS_PAY);
                criteria1.andUidEqualTo(request.getUid());
                orderExample.setOrderByClause("order_time desc");
                Page page = new Page(0, 2);//第一页，2条
                orderExample.setPage(page);
                List<TbGameOrder> gameOrders = gameOrderMapper.selectByExample(orderExample);
                if (gameOrders.size() == 2 && gameOrders.get(0).getPayAmount().doubleValue() == 0 && gameOrders.get(1).getPayAmount().doubleValue() == 0) {
                    logger.info("用户连续2次产生0元订单！产生验证码！");
                    return APIResponse.returnSuccess(null, ApiResponseEnum.WAIT_SMS_CODE_CONFIRM);
                }
            }
        }
        //锁定库存
        if (!gameSystemDao.updateGameStorage(request.getGameId(), signCount)) {
            logger.info("锁定gameid={}报名库存，库存量减{}失败！库存量不足！", request.getGameId(), signCount);
            return APIResponse.returnFail(GameSignUpEnum.GAME_SIGN_USER_IS_FULL.getId(), GameSignUpEnum.GAME_SIGN_USER_IS_FULL.getName());
        }
        logger.info("开始支付验证-------------------");
        return prepareCallPay(tbGameEvent, signCount, request, gamePlaceOrder);


    }

    @Override
    public APIResponse prepareCallPay(TbGameEvent tbGameEvent, int signCount, ReqPay request, GamePlaceOrder gamePlaceOrder) {
        BigDecimal price = tbGameEvent.getPrice().multiply(new BigDecimal(signCount));
        double leftPay = price.doubleValue();
        double eggPay = 0D;
        boolean payFinish = false;
        if (tbGameEvent.getPayType() > 0) {
            //线下支付，作为免费活动，不走订单系统
            payFinish = true;
            leftPay = 0;
            eggPay = 0;
        }
        if (request.getEnableEggPay() == 1 && !payFinish) {
            logger.info("开始支付验证--------------报名使用鸟蛋，开始验证鸟蛋数量：");
            OtherPayWay eggpay = eggPay(request.getUid(), price,signCount);
            Double eggRMB = eggpay.getToRMB();
            if (eggRMB >= leftPay) {
                eggPay = leftPay;
                leftPay = 0D;
                payFinish = true;
            } else {
                leftPay = leftPay - eggRMB;
                eggPay = eggRMB;
            }
            if (!eggRMB.equals(request.getEggToRMB())) {
                logger.info("请求和验证的鸟蛋数量不一致，支付失败！并还原库存！");
                gameSystemDao.updateGameStorage(request.getGameId(), -1);
                return APIResponse.returnFail(GameSignUpEnum.EGG_CANUSE_AMOUNT_ERROR.getId(), GameSignUpEnum.EGG_CANUSE_AMOUNT_ERROR.getName());
            }
        }
        TbGameOrder gameOrder = new TbGameOrder();
        RespPreOrder preOrder = new RespPreOrder();
        if (leftPay > 0 || eggPay > 0) {
            logger.info("鸟蛋或者金额支付大于0，走订单系统下单！");

            ReqOrderSave reqOrderSave = new ReqOrderSave();
            List<ReqPayInfo> list = Lists.newArrayList();
            if (leftPay > 0) {
                ReqPayInfo reqPayInfo = new ReqPayInfo();
                DecimalFormat df = new DecimalFormat("#####.00");
                reqPayInfo.setAmount(new BigDecimal(df.format(leftPay)));
                reqPayInfo.setPayId(request.getPayType());
                reqPayInfo.setPayType(GameConstants.MONEY_PAY_DESC);
                logger.info("用户支付uid={}，rmb支付payInfo={}", request.getUid(), gson.toJson(reqPayInfo));
                list.add(reqPayInfo);
            }
            if (eggPay > 0) {
                ReqPayInfo reqPayInfo = new ReqPayInfo();
                reqPayInfo.setAmount(BigDecimal.valueOf(eggPay * 10));
                reqPayInfo.setPayId(GameConstants.PAY_WAY_FOR_AGES);
                reqPayInfo.setPayType(GameConstants.OTHER_PAY_NAME_EGG);
                logger.info("用户支付uid={}，鸟蛋支付payInfo={}", request.getUid(), gson.toJson(reqPayInfo));
                list.add(reqPayInfo);
                if (tbGameEvent.getType() == 0) {
                    reqOrderSave.setEggReceiver("百灵鸟");
                } else {
                    RespClubPlainInfo respClubPlainInfo = null;
                    List<Integer> clubIds = new ArrayList<>();
                    clubIds.add(tbGameEvent.getClubId());
                    Map<Integer, RespClubPlainInfo> map = clubOperService.getClubBaseInfoList(clubIds);
                    if (map != null) {
                        respClubPlainInfo = map.get(tbGameEvent.getClubId());
                    }
                    if (respClubPlainInfo != null) {
                        reqOrderSave.setEggReceiver(respClubPlainInfo.getClubName());
                    }
                }
                reqOrderSave.setEggInfo(tbGameEvent.getName() + "报名费");
            }
            reqOrderSave.setPayInfos(list);
            reqOrderSave.setSourceSystemId(Constants.STADIUM_SYSTEM_CODE);
            reqOrderSave.setSourceBusinessId(Constants.STADIUM_GAME_SIGN_BUSINESS_CODE);
            reqOrderSave.setOrderAmount(BigDecimal.valueOf(leftPay + eggPay));
            reqOrderSave.setChannelId(GameConstants.DEFAULT_CHANNEL);
            reqOrderSave.setContactMobile(GameConstants.CONTRACT_MOBILE);
            reqOrderSave.setContactName(GameConstants.CONTRACT_NAME);


            reqOrderSave.setNotifyURL(GameConstants.NOTIFYURL);

            reqOrderSave.setNotifyURL(payUrl);
            reqOrderSave.setCloseNotifyURL(expireUrl);
            reqOrderSave.setExtraParam(CollectionUtils.isNotEmpty(request.getUids()) ? gson.toJson(request.getUids()) : "");
            reqOrderSave.setOutTradeNo(CommonUtils.generateBusinessOrderNo(Constants.STADIUM_SYSTEM, request.getUid()));
            reqOrderSave.setService(GameConstants.SERVICE);
            reqOrderSave.setPayTimeOut(GameConstants.PAYTIMETOU);
            reqOrderSave.setUid(request.getUid());
            reqOrderSave.setOrderDescribe(GameConstants.ORDERDESC);
            reqOrderSave.setVer(request.getVer());

            List<ReqProductDetail> list1 = new ArrayList<ReqProductDetail>();
            ReqProductDetail reqProductDetail = new ReqProductDetail();
            reqProductDetail.setShowURL(GameConstants.PRODUCT_URL);


            DecimalFormat df = new DecimalFormat("#####.00");
            reqProductDetail.setPrice(new BigDecimal(df.format(tbGameEvent.getPrice().doubleValue())));
            reqProductDetail.setProductDesc(GameConstants.PRODUCT_DESC);
            reqProductDetail.setProductId(tbGameEvent.getId().toString());
            reqProductDetail.setProductName(tbGameEvent.getName());
            reqProductDetail.setProductURL(GameConstants.PRODUCT_ICON);
            reqProductDetail.setQuantity(GameConstants.QUANLITY);

            list1.add(reqProductDetail);
            reqOrderSave.setProductDetailList(list1);
            reqOrderSave.setPlatformType(request.getPlatformType());
            APIRequest<ReqOrderSave> reqOrderSaveAPIRequest = new APIRequest<>();
            reqOrderSaveAPIRequest.setData(reqOrderSave);
            if(request.getPayType() == 3) {
                reqOrderSave.setBuyerAccount(request.getOpenId());
                reqOrderSave.setMchId(3);
            }else{
                reqOrderSave.setMchId(2);
            }
            if(request.getPayType() == 14){
                reqOrderSave.setShowURLForH5(request.getShowURLForH5());
                reqOrderSave.setReturnUrlForH5(request.getReturnUrlForH5());
            }
            APIResponse<RespPreOrder> respPreOrderAPIResponse = orderPayService.submitOrder(reqOrderSaveAPIRequest);
            logger.info("调用订单系统，响应：{}", new Gson().toJson(respPreOrderAPIResponse));

            if (null != respPreOrderAPIResponse && respPreOrderAPIResponse.isRet()) {
                preOrder = respPreOrderAPIResponse.getData();
                if (respPreOrderAPIResponse.getData().getResult().equals(
                        OrderStatusEnum.USER_PAY_SUCCESS.getCode())) {
                    gameOrder.setOrderStatus(GameConstants.SUCCESS_ORDER);
                    gameOrder.setPayWait(GameConstants.SUCCESS_PAY);
                    gameOrder.setIsClose(GameConstants.ORDER_IS_CLOST_YES);
                } else if (respPreOrderAPIResponse.getData().getResult().equals(
                        OrderStatusEnum.WAIT_BUYPER_PAY.getCode())) {
                    gameOrder.setOrderStatus(GameConstants.WAIT_ORDER);
                    gameOrder.setPayWait(GameConstants.ON_PAYING);
                    gameOrder.setIsClose(GameConstants.ORDER_IS_CLOST_NO);
                }
                gameOrder.setTradeOrderNo(preOrder.getOutTradeNo());
                gameOrder.setGameOrderNo(preOrder.getOrderNo());
            } else {
                gameSystemDao.updateGameStorage(request.getGameId(), -signCount);
                return APIResponse.returnFail("报名失败！");
            }
        } else {
            //免费活动的报名或者线下支付
            RespPreOrder respPreOrder = new RespPreOrder();
            Integer result = directOrder(request.getClubId(), gamePlaceOrder, request.getUid(), 0, respPreOrder,request.getIsHelpSign(),request.getUids());
            if (result == 1) {
                logger.info("用户uid = {}，以俱乐部clubId={}报名参加免费活动gameid = {}，生成订单成功！", request.getUid(), request.getClubId(), request.getGameId());
                if (gameEventTransfer.getGameCategoryById(tbGameEvent.getGameCategoryType().intValue()).getMinNum() == 2
                        && gameEventTransfer.getGameCategoryById(tbGameEvent.getGameCategoryType().intValue()).getMaxNum() == 2 && request.getUids() != null) {
                    //双打队伍插入
                    updateUserSignCount(request.getUids(), tbGameEvent.getType());
                    insertDoubleTeam(tbGameEvent, request.getUids(), respPreOrder.getOutTradeNo());
                } else {
                    //判断代报名
                    if(request.getIsHelpSign()==1){
                        updateTbRecentUser(request.getUid(),request.getUids());
                        updateUserSignCount(request.getUids(),tbGameEvent.getType());
                        //dfadfad
                        for(int uid : request.getUids()){
                            insertNewTeam(tbGameEvent, uid, request.getClubId(), gameOrder.getTradeOrderNo(),true);
                        }
                    }else {
                        List<Integer> list = Lists.newArrayList();
                        list.add(request.getUid());
                        updateUserSignCount(list,tbGameEvent.getType());
                        insertNewTeam(tbGameEvent, request.getUid(), request.getClubId(), gameOrder.getTradeOrderNo(), true);
                    }
                }
                return APIResponse.returnSuccess(respPreOrder);
            } else {
                gameSystemDao.updateGameStorage(request.getGameId(), -signCount);
                return APIResponse.returnFail("报名失败！");
            }
        }
        gameOrder.setGameEventId(request.getGameId());
        gameOrder.setOrderAmount(tbGameEvent.getPrice().multiply(new BigDecimal(signCount)));
        gameOrder.setPayAmount(BigDecimal.valueOf(leftPay));
        gameOrder.setClubAmount(BigDecimal.valueOf(0));
        gameOrder.setAccumulate((int) (eggPay * 10));
        Calendar nowTime = Calendar.getInstance();
        gameOrder.setOrderTime(nowTime.getTime());
        nowTime.add(Calendar.MINUTE, 5);
        gameOrder.setDeadTime(nowTime.getTime());
        gameOrder.setUid(request.getUid());
        gameOrder.setType(tbGameEvent.getType());
        gameOrder.setSrcId(request.getPlatformType());
        if (tbGameEvent.getGameTeamType() == 1) {
            gameOrder.setClubid(request.getClubId());
        }
        gameOrder.setPayType(request.getPayType().byteValue());
        gameOrder.setGamePlace(gamePlaceOrder.getPlaceName());
        gameOrder.setGameTeamType(tbGameEvent.getGameTeamType());
        gameOrder.setPayTime(new Date());
        gameOrder.setContact(tbGameEvent.getManagerName());

        gameOrder.setContractMobile(tbGameEvent.getManagerMobile());
        gameOrder.setGameName(tbGameEvent.getName());
        gameOrder.setGameName(tbGameEvent.getName());
        //代报名
        if(request.getIsHelpSign() == 1){
            gameOrder.setIsHelpSign((byte) 1);
            gameOrder.setHelpSignUids(new Gson().toJson(request.getUids()));
        }

        if (gameSystemDao.insertGameOrder(gameOrder).getTradeOrderNo() != null) {
            if (gameOrder.getOrderStatus() == GameConstants.WAIT_ORDER) {
                return APIResponse.returnSuccess(preOrder);
            } else {
                if (gameEventTransfer.getGameCategoryById(tbGameEvent.getGameCategoryType().intValue()).getMinNum() == 2
                        && gameEventTransfer.getGameCategoryById(tbGameEvent.getGameCategoryType().intValue()).getMaxNum() == 2) {
                    //双打队伍插入
                    insertDoubleTeam(tbGameEvent, request.getUids(), gameOrder.getTradeOrderNo());
                } else {
                    //如果是代报名：
                    if(request.getIsHelpSign()==1){
                        updateTbRecentUser(request.getUid(),request.getUids());
                        updateUserSignCount(request.getUids(),tbGameEvent.getType());
                        //dfadfad
                        for(int uid : request.getUids()){
                            insertNewTeam(tbGameEvent, uid, request.getClubId(), gameOrder.getTradeOrderNo(),true);
                        }
                    }else {
                        List<Integer> list = Lists.newArrayList();
                        list.add(request.getUid());
                        updateUserSignCount(list,tbGameEvent.getType());
                        insertNewTeam(tbGameEvent, request.getUid(), request.getClubId(), gameOrder.getTradeOrderNo(), true);
                    }

                }
                return APIResponse.returnSuccess(preOrder);
            }
        } else {
            gameSystemDao.updateGameStorage(request.getGameId(), -signCount);
            return APIResponse.returnFail("下单失败");
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public APIResponse orderPayOperate(OrderNotifyMsg orderNotifyMsg) {
        if (orderNotifyMsg.getResultCode() != null) {
            TbGameOrderExample orderExample = new TbGameOrderExample();
            TbGameOrderExample.Criteria criteria = orderExample.createCriteria();
            criteria.andTradeOrderNoEqualTo(orderNotifyMsg.getOutTradeNo());
            List<TbGameOrder> orders = gameOrderMapper.selectByExample(orderExample);
            if (CollectionUtils.isEmpty(orders)) {
                logger.error("支付成功回调查询订单失败！");
                return APIResponse.returnSuccess();
            }
            TbGameOrder tbGameOrder = orders.get(0);
            if (tbGameOrder.getPayNotify() == 1) {
                logger.error("支付回调已经执行过，停止回调！");
                return APIResponse.returnSuccess();
            }
            byte isHelpSign = tbGameOrder.getIsHelpSign();
            List<Integer> helpSignUids = new ArrayList<>();
            if(isHelpSign == 1){
                Type type = new TypeToken<List<Integer>>() {
                }.getType();
                helpSignUids = new Gson().fromJson(tbGameOrder.getHelpSignUids(),type);
            }
            TbGameOrder gameOrder = new TbGameOrder();
            switch (orderNotifyMsg.getResultCode()) {
                case OrderNotifyMsg.RESULT_CODE_USER_PAY_SUCCESS:
                    //更新订单信息
                    gameOrder.setPayWait(GameConstants.SUCCESS_PAY);
                    gameOrder.setOrderStatus(GameConstants.SUCCESS_ORDER);
                    gameOrder.setIsClose(GameConstants.ORDER_IS_CLOST_YES);
                    gameOrder.setTradeOrderNo(orderNotifyMsg.getOutTradeNo());
                    gameOrder.setGameOrderNo(orderNotifyMsg.getOrderNo());
                    gameOrder.setPayTime(new Date());
                    gameOrder.setPayNotify((byte) 1);
                    TbGameOrder order = gameOrderDao.updateOrderByOrderTradeId(gameOrder);
                    if (null != order && order.getId() > 0) {
                        TbGameEvent gameEvent = gameEventMapper.selectByPrimaryKey(order.getGameEventId());
                        if (gameEventTransfer.getGameCategoryById(gameEvent.getGameCategoryType().intValue()).getMinNum() == 2
                                && gameEventTransfer.getGameCategoryById(gameEvent.getGameCategoryType().intValue()).getMaxNum() == 2) {
                            //用户双打
                            Gson gson = new Gson();
                            List<Integer> uidList = gson.fromJson(orderNotifyMsg.getExtraParam(), new TypeToken<List<Integer>>() {
                            }.getType());
                            if(null == uidList || uidList.size() < 1){
                               if(orderNotifyMsg.getUid() != null){
                                   uidList = new ArrayList<>();
                                   uidList.add(orderNotifyMsg.getUid());
                               }
                            }
                            insertDoubleTeam(gameEvent, uidList, gameOrder.getTradeOrderNo());
                        } else {
                            //判断代报名
                            if(isHelpSign == 1){
                                updateTbRecentUser(tbGameOrder.getUid(),helpSignUids);
                                updateUserSignCount(helpSignUids,gameEvent.getType());
                                //dfadfad
                                for(int uid : helpSignUids){
                                    insertNewTeam(gameEvent, uid, gameEvent.getClubId(), gameOrder.getTradeOrderNo(),true);
                                }
                            }else {
                                List<Integer> list = Lists.newArrayList();
                                list.add(order.getUid());
                                updateUserSignCount(list,order.getType());
                                insertNewTeam(gameEvent, order.getUid(), order.getClubid(), gameOrder.getTradeOrderNo(),true);
                            }
                        }
                    }
                    break;
                case OrderNotifyMsg.RESULT_CODE_USER_PAY_FAIL:
                    gameOrder.setPayWait(GameConstants.FAIL_PAY);
                    gameOrder.setOrderStatus(GameConstants.FAIL_ORDER);
                    gameOrder.setIsClose(GameConstants.ORDER_IS_CLOST_YES);
                    gameOrder.setTradeOrderNo(orderNotifyMsg.getOrderNo());
                    gameOrder.setPayNotify((byte) 1);
                    TbGameOrder order1 = gameOrderDao.updateOrderByOrderTradeId(gameOrder);
                    TbGameEvent gameEvent = gameEventMapper.selectByPrimaryKey(order1.getGameEventId());
                    int count = signCount(gameEvent,isHelpSign,helpSignUids.size());
                    gameSystemDao.updateGameStorage(order1.getGameEventId(), -count);
                    break;
            }
        }
        return APIResponse.returnSuccess();
    }


    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public APIResponse expireCallBack(String orderNo) {
        // 支付超时
        TbGameOrderExample example = new TbGameOrderExample();
        TbGameOrderExample.Criteria criteria = example.createCriteria();
        criteria.andTradeOrderNoEqualTo(orderNo);
        List<TbGameOrder> orders = gameOrderMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(orders)) {
            TbGameOrder gameOrder = orders.get(0);
            if (gameOrder.getExpireNotify() == 1) {
                return APIResponse.returnSuccess();
            }
            byte isHelpSign = gameOrder.getIsHelpSign();
            List<Integer> helpSignUids = new ArrayList<>();
            if(isHelpSign == 1){
                Type type = new TypeToken<List<Integer>>() {
                }.getType();

                helpSignUids = new Gson().fromJson(gameOrder.getHelpSignUids(),type);
            }
            if (gameOrder.getIsClose() == GameConstants.ORDER_IS_CLOST_NO) {
                TbGameOrder tbGameOrder = new TbGameOrder();
                tbGameOrder.setIsClose(GameConstants.ORDER_IS_CLOST_YES);
                tbGameOrder.setPayWait(GameConstants.FAIL_PAY);
                tbGameOrder.setOrderStatus(GameConstants.EXPIRE_ORDER);
                tbGameOrder.setExpireNotify((byte) 1);
                gameOrderMapper.updateByExampleSelective(tbGameOrder, example);
                TbGameEvent gameEvent = gameEventMapper.selectByPrimaryKey(orders.get(0).getGameEventId());
                int count = signCount(gameEvent,isHelpSign,helpSignUids.size());
                //gameSystemDao.updateGameStorage(order1.getGameEventId(), -count);
                gameSystemDao.updateGameStorage(gameOrder.getGameEventId(), -count);
            }
        }
        return APIResponse.returnSuccess();
    }

    @Override
    public APIResponse refundCallback(RefundNotifyMsg refundNotifyMsg) {
        TbGameOrder gameOrder = new TbGameOrder();
        if (RefundStatusEnum.SUCCESS.getId() == refundNotifyMsg.getRefundState()) {
            logger.info("消息:订单退款成功：订单系统订单号：{} 退款状态：{}", refundNotifyMsg.getOutTradeNo(), refundNotifyMsg.getRefundState());
            gameOrder.setOrderStatus(GameConstants.SUCCESS_REFUND);
            TbGameOrderExample example = new TbGameOrderExample();
            TbGameOrderExample.Criteria criteria = example.createCriteria();
            criteria.andTradeOrderNoEqualTo(refundNotifyMsg.getOutTradeNo());
            gameOrderMapper.updateByExampleSelective(gameOrder, example);

            List<TbGameOrder> orders = gameOrderMapper.selectByExample(example);
            if (CollectionUtils.isNotEmpty(orders)) {
                TbGameOrder tbGameOrder = orders.get(0);
                int gameId = tbGameOrder.getGameEventId();

                List<Integer> uids = new ArrayList<>();
                Gson gson = new Gson();
                if(tbGameOrder.getIsHelpSign().intValue() == 1){
                    uids = gson.fromJson(tbGameOrder.getHelpSignUids(),new TypeToken<List<Integer>>() {
                    }.getType());
                }else{
                    for (TbGameOrder gameOrder1 : orders) {
                        uids.add(gameOrder1.getUid());
                    }
                }
                //删除用户报名信息
                TbGameEventTeam record = new TbGameEventTeam();
                record.setIsDelete(GameConstants.IS_DELETE);

                TbGameEventTeamExample example2 = new TbGameEventTeamExample();
                TbGameEventTeamExample.Criteria criteria2 = example2.createCriteria();
                criteria2.andGameEventIdEqualTo(gameId);
                criteria2.andUidIn(uids);
                gameEventTeamMapper.updateByExampleSelective(record,example2);

                //还原库存
                gameSystemDao.updateGameStorage(gameId, -1);
            }
        }
        return APIResponse.returnSuccess();
    }

    @Override
    public void orderRefundOperate(MessageExt messageExt) {

    }

    @Override
    public APIResponse<List<User>> queryGameUser(ReqGameUser request) {
        TbUserGameScheduleExample tbUserGameScheduleExample = new TbUserGameScheduleExample();
        TbUserGameScheduleExample.Criteria criteria = tbUserGameScheduleExample.createCriteria();
        criteria.andGameScheduleIdEqualTo(request.getGameScheduleId());
        List<TbUserGameSchedule> list = userGameScheduleMapper.selectByExample(tbUserGameScheduleExample);
        List<User> users = Lists.newArrayList();
        for (TbUserGameSchedule userGameSchedule : list) {
            User user = new User();
            RespUserInfoBase userInfo = baseService.queryUserMsg(userGameSchedule.getUid());
            BeanUtils.copyProperties(userInfo, user);
            users.add(user);
        }
        return APIResponse.returnSuccess(users);
    }

    @Override
    public APIResponse abstain(ReqAbstain request) {
        TbGameEvent gameEvent = gameEventMapper.selectByPrimaryKey(request.getGameId());
        if (null == gameEvent) {
            return APIResponse.returnFail("弃权失败！");
        }
        TbGameEventTeamExample example = new TbGameEventTeamExample();
        TbGameEventTeamExample.Criteria criteria = example.createCriteria();
        criteria.andGameEventIdEqualTo(request.getGameId());
        if (gameEvent.getGameTeamType() == 0) {
            criteria.andUidEqualTo(request.getUid());
        } else if (gameEvent.getGameTeamType() == 1) {
            criteria.andClubIdEqualTo(request.getClubId());
        }
        TbGameEventTeam tbGameEventTeam = new TbGameEventTeam();
        tbGameEventTeam.setIsForfeit((byte) 1);
        gameEventTeamMapper.updateByExampleSelective(tbGameEventTeam, example);
        return APIResponse.returnSuccess("弃权成功！");
    }

    /**
     * 调用订单系统给用户退款
     */
    @Override
    public APIResponse<RefundStatusEnum> refoundUserPay(TbGameOrder order, TbGameEvent tbGameEvent) {
        if (order.getOrderAmount().doubleValue() == 0) {
            successRefund(order.getTradeOrderNo());
            return APIResponse.returnSuccess();
        }
        APIRequest<ReqOrderRefund> orderRefundAPIRequest = new APIRequest<>();
        ReqOrderRefund reqOrderRefund = new ReqOrderRefund();
        reqOrderRefund.setSourceSystemId(Constants.STADIUM_SYSTEM_CODE);
        reqOrderRefund.setSourceBusinessId(Constants.STADIUM_GAME_SIGN_BUSINESS_CODE);
        reqOrderRefund.setOrderNo(order.getGameOrderNo());
        reqOrderRefund.setOutTradeRefundNo("REFUND_" + CommonUtils.generateOrderNo(order.getUid()));
        reqOrderRefund.setReason("比赛取消");
        reqOrderRefund.setUid(order.getUid());
        reqOrderRefund.setRefundNotifyURL(refundUrl);
        reqOrderRefund.setNeedAudit(false);

        DecimalFormat df = new DecimalFormat("#####.00");
        reqOrderRefund.setAmount(new BigDecimal(df.format(order.getOrderAmount())));
        //退款产品
        List<ReqRefundProduct> reqRefundProducts = new ArrayList<>();
        ReqRefundProduct reqRefundProduct = new ReqRefundProduct();

        reqRefundProduct.setPrice(tbGameEvent.getPrice());

        reqRefundProduct.setQuantity(1);
        reqRefundProduct.setProductName(tbGameEvent.getName());
        reqRefundProduct.setProductId(tbGameEvent.getId().toString());
        reqRefundProducts.add(reqRefundProduct);

        List<ReqRefundPayInfo> reqRefundPayInfoList = new ArrayList<ReqRefundPayInfo>();
        if (order.getPayAmount().doubleValue() > 0) {
            ReqRefundPayInfo rmb = new ReqRefundPayInfo();
            rmb.setPayId(order.getPayType().intValue());
            rmb.setRefundAmount(new BigDecimal(df.format(order.getPayAmount())));
            reqRefundPayInfoList.add(rmb);
        }
        if (order.getAccumulate() > 0) {
            ReqRefundPayInfo ages = new ReqRefundPayInfo();
            ages.setPayId(PayWayEnum.PAY_WAY_FOR_AGES.getPayId());
            ages.setRefundAmount(BigDecimal.valueOf(order.getAccumulate()));
            reqRefundPayInfoList.add(ages);
        }
        reqOrderRefund.setReqRefundPayInfos(reqRefundPayInfoList);
        reqOrderRefund.setRefundProductList(reqRefundProducts);
        orderRefundAPIRequest.setData(reqOrderRefund);
        APIResponse<RefundStatusEnum> response = orderPayService.refundApply(orderRefundAPIRequest);
        logger.info("退款响应：{}", gson.toJson(response.getData()));
        onRefund(order.getGameOrderNo());
        return response;
    }

    /**
     * 申请退款中
     *
     * @param orderNo
     */
    private void onRefund(String orderNo) {
        TbGameOrderExample tbGameOrderExample = new TbGameOrderExample();
        TbGameOrderExample.Criteria criteria = tbGameOrderExample.createCriteria();
        criteria.andTradeOrderNoEqualTo(orderNo);
        TbGameOrder tbGameOrder = new TbGameOrder();
        tbGameOrder.setOrderStatus(GameConstants.ON_REFUND);
        tbGameOrder.setRefundTime(new Date());
        gameOrderMapper.updateByExampleSelective(tbGameOrder, tbGameOrderExample);
    }

    /**
     * 申请退款成功
     *
     * @param orderNo
     */
    private void successRefund(String orderNo) {
        TbGameOrderExample tbGameOrderExample = new TbGameOrderExample();
        TbGameOrderExample.Criteria criteria = tbGameOrderExample.createCriteria();
        criteria.andTradeOrderNoEqualTo(orderNo);
        TbGameOrder tbGameOrder = new TbGameOrder();
        tbGameOrder.setOrderStatus(GameConstants.SUCCESS_REFUND);
        gameOrderMapper.updateByExampleSelective(tbGameOrder, tbGameOrderExample);
    }

    @Override
    public void refound(Integer gameId) {
        logger.info("开始给已经报名比赛gameid={}的用户退款", gameId);
        TbGameEvent tbGameEvent = gameEventMapper.selectByPrimaryKey(gameId);
        if (tbGameEvent == null) {
            logger.error("比赛不存在或者已经取消，不能退款！");
        }
        if (tbGameEvent.getIsDelete() == GameConstants.IS_DELETE) {
            logger.error("比赛已经取消过，不能取消！");
        }
        if (tbGameEvent.getEndTime().before(new Date())) {
            logger.error("比赛已经结束，不能退款！");
        }
        TbGameOrderExample example = new TbGameOrderExample();
        TbGameOrderExample.Criteria criteria = example.createCriteria();
        criteria.andGameEventIdEqualTo(gameId);
        criteria.andIsCloseEqualTo(GameConstants.ORDER_IS_CLOST_YES);
        criteria.andPayWaitEqualTo(GameConstants.SUCCESS_PAY);
        criteria.andOrderStatusEqualTo(GameConstants.SUCCESS_ORDER);
        List<TbGameOrder> orders = gameOrderMapper.selectByExample(example);

        if (!CollectionUtils.isEmpty(orders)) {
            logger.info("查询到支付成功的订单{}个需要退订，下面开始退款：", orders.size());
            for (TbGameOrder order : orders) {
                logger.info("给用户报名用户uid={}退款，需要退人民币：{},鸟蛋:{}", order.getUid(), order.getPayAmount(), order.getAccumulate());
                refoundUserPay(order, tbGameEvent);
                onRefund(order.getTradeOrderNo());
            }
        }
    }

    @Override
    public APIResponse setterUp(Integer gameId) {
        //查询所有支付订单
        TbGameEvent gameEvent = gameEventMapper.selectByPrimaryKey(gameId);
        if (gameEvent.getType() == 0) {
            return APIResponse.returnFail("不是俱乐部比赛，不能结算");
        }
        //免费活动，不走结算流程，直接退出
        if (gameEvent.getPayType() == 1) {
            return APIResponse.returnFail("免费活动，不走结算！");
        }
        int clubId = gameEvent.getClubId();
        BigDecimal singlePrice = gameEvent.getPrice();
        if (gameEvent.getIsDelete() != GameConstants.IS_DELETE) {
            //赛事没有关闭
            TbGameOrderExample tbGameOrderExample = new TbGameOrderExample();
            TbGameOrderExample.Criteria criteria = tbGameOrderExample.createCriteria();
            criteria.andGameEventIdEqualTo(gameId);
            criteria.andPayWaitEqualTo(GameConstants.SUCCESS_PAY);
            criteria.andOrderStatusEqualTo(GameConstants.SUCCESS_ORDER);
            List<TbGameOrder> orders = gameOrderMapper.selectByExample(tbGameOrderExample);
            if (!CollectionUtils.isEmpty(orders)) {
                BigDecimal amount = new BigDecimal(0);
                for (TbGameOrder tbGameOrder : orders) {
                    amount = amount.add(tbGameOrder.getOrderAmount());
                }
                String orderNO = CommonUtils.generateOrderNo(gameId);
                APIResponse apiResponse = clubOpenService.updateClubOnlineAccountBalance(clubId, gameId, orderNO, amount, "赛事结算", true);

                if (null != apiResponse && apiResponse.isRet()) {
                    List<ReqClubSettlementInfo> list = Lists.newArrayList();

                    ReqClubSettlementInfo all = new ReqClubSettlementInfo();

                    all.setClubId(clubId);
                    all.setActivityId(gameId);

                    BigDecimal eggAmount = BigDecimal.valueOf(0);
                    BigDecimal payAmount = BigDecimal.valueOf(0);

                    for (TbGameOrder order : orders) {
                        ReqClubSettlementInfo reqClubSettlementInfo = new ReqClubSettlementInfo();
                        reqClubSettlementInfo.setUid(order.getUid());
                        reqClubSettlementInfo.setActivityId(gameId);
                        reqClubSettlementInfo.setClubId(gameEvent.getClubId());

                        if (order.getAccumulate() != null && order.getAccumulate() > 0) {
                            BigDecimal egg = BigDecimal.valueOf(order.getAccumulate()).divide(BigDecimal.valueOf(10));
                            eggAmount = eggAmount.add(egg);
                            reqClubSettlementInfo.setEggDeductionFee(egg);
                        }

                        if (order.getPayAmount() != null && order.getPayAmount().doubleValue() > 0) {
                            BigDecimal money = order.getPayAmount();
                            payAmount = payAmount.add(money);
                            reqClubSettlementInfo.setPayFee(order.getPayAmount());
                        }
                        reqClubSettlementInfo.setIntegralDeductionFee(BigDecimal.valueOf(0));
                        reqClubSettlementInfo.setRemark("用户uid=" + order.getUid() + "报名费" + order.getOrderAmount());
                        reqClubSettlementInfo.setRealPayFee(order.getOrderAmount());
                        list.add(reqClubSettlementInfo);
                    }
                    all.setRemark("赛事所有人的报名费");
                    all.setRealPayFee(amount);
                    all.setIntegralDeductionFee(BigDecimal.valueOf(0));
                    all.setPayFee(payAmount);
                    all.setEggDeductionFee(eggAmount);
                    return clubOpenService.settlementClubGameActivity(all, list);
                }
            }
        }
        return APIResponse.returnFail("结算失败!");
    }


    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Map<Integer, Integer> outerGameSignUp(List<Integer> uids, Integer gameId,boolean flag) {
        //判断用户是否已经报过名
        TbGameEventTeamExample teamExample = new TbGameEventTeamExample();
        TbGameEventTeamExample.Criteria criteria = teamExample.createCriteria();
        criteria.andGameEventIdEqualTo(gameId);
        criteria.andUidEqualTo(uids.get(0));
        criteria.andIsDeleteEqualTo(GameConstants.IS_NOT_DELETE);
        List<TbGameEventTeam> gameEventTeams = gameEventTeamMapper.selectByExample(teamExample);
        if(gameEventTeams.size() > 0 ){
            return null;
        }
        Map<Integer, Integer> teamResult = new HashMap<>();
        if (uids == null || uids.size() < 0 || gameId == null) {
            return null;
        }
        //校验活动的有效性
        TbGameEvent tbGameEvent = gameEventMapper.selectByPrimaryKey(gameId);
        if (null == tbGameEvent || null == tbGameEvent.getId() || tbGameEvent.getId() < 1) {
            logger.info("用户uid={},支付比赛gameid={}查询该比赛时该比赛不存在！", uids, gameId);
            return null;
        }
        if (tbGameEvent.getPayType() == 0) {
            //分享页报名只支持免费活动！
            return null;
        }
        int signCount = signCount(tbGameEvent,0,0);
        //锁定库存
        if(!flag) {
            if (!gameSystemDao.updateGameStorage(gameId, signCount)) {
                logger.info("锁定gameid={}报名库存，库存量减{}失败！库存量不足！", gameId, signCount);
                return null;
            }
        }else {
            if (gameEventTransfer.getGameCategoryById(tbGameEvent.getGameCategoryType().intValue()).getMinNum() == 2
                    && gameEventTransfer.getGameCategoryById(tbGameEvent.getGameCategoryType().intValue()).getMaxNum() == 2) {

                TbGameEventTeamExample eventTeamExample = new TbGameEventTeamExample();
                TbGameEventTeamExample.Criteria criteria1 = eventTeamExample.createCriteria();
                criteria1.andGameEventIdEqualTo(gameId);
                criteria1.andIsDeleteEqualTo((byte) 0);
                int count = 4 - gameEventTeamMapper.countByExample(eventTeamExample);
                if(count < 1){
                    logger.info("锁定gameid={}报名库存，库存量减{}失败！库存量不足！", gameId, signCount);
                    return null;
                }
                if(count == 1){
                    if (!gameSystemDao.updateGameStorage(gameId, signCount)) {
                        logger.info("锁定gameid={}报名库存，库存量减{}失败！库存量不足！", gameId, signCount);
                        return null;
                    }
                }
            }else{
                if (!gameSystemDao.updateGameStorage(gameId, signCount)) {
                    logger.info("锁定gameid={}报名库存，库存量减{}失败！库存量不足！", gameId, signCount);
                    return null;
                }
            }
        }


        //更新报名人数
        officialGameCache.delGameEvent(gameId);

        GamePlaceOrder gamePlaceOrder = new GamePlaceOrder();
        wrapTBgameEvent(tbGameEvent, gamePlaceOrder);

        //免费活动的报名或者线下支付
        RespPreOrder respPreOrder = new RespPreOrder();
        Integer result = directOrder(0, gamePlaceOrder, uids.get(0), 0, respPreOrder,0,null);

        if (result == 1) {
            try {
                if (gameEventTransfer.getGameCategoryById(tbGameEvent.getGameCategoryType().intValue()).getMinNum() == 2 && gameEventTransfer.getGameCategoryById(tbGameEvent.getGameCategoryType().intValue()).getMaxNum() == 2) {
                    //双打队伍插入
                    updateUserSignCount(uids,tbGameEvent.getType());
                    Map<Integer, Integer> doubleResult = insertDoubleTeamWithTeam(tbGameEvent, uids, respPreOrder.getOutTradeNo(), flag);
                    teamResult.putAll(doubleResult);
                } else {


                    int team = insertNewTeam(tbGameEvent, uids.get(0), 0, respPreOrder.getOutTradeNo(),flag);
                    teamResult.put(uids.get(0), team);
                    updateUserSignCount(uids,tbGameEvent.getType());

                }
            }catch (Exception e){
                //还原库存
                if(!flag || !(gameEventTransfer.getGameCategoryById(tbGameEvent.getGameCategoryType().intValue()).getMinNum() == 2
                        && gameEventTransfer.getGameCategoryById(tbGameEvent.getGameCategoryType().intValue()).getMaxNum() == 2)) {
                    gameSystemDao.updateGameStorage(gameId, -signCount);
                }
                return null;
            }
            return teamResult;
        } else {
            if(!flag || !(gameEventTransfer.getGameCategoryById(tbGameEvent.getGameCategoryType().intValue()).getMinNum() == 2
                    && gameEventTransfer.getGameCategoryById(tbGameEvent.getGameCategoryType().intValue()).getMaxNum() == 2)) {
                gameSystemDao.updateGameStorage(gameId, -signCount);
            }
            return null;
        }
    }

    @Override
    public APIResponse<RespGameResult> checkSign(ReqSignResult request) {
        RespGameResult respGameResult = new RespGameResult();
        respGameResult.setUid(request.getUid());
        respGameResult.setGameid(request.getGameId());
        //个人对抗赛，判断是否已经报过名
        TbGameEventTeamExample teamExample = new TbGameEventTeamExample();
        TbGameEventTeamExample.Criteria criteria = teamExample.createCriteria();
        criteria.andUidEqualTo(request.getUid());
        criteria.andGameEventIdEqualTo(request.getGameId());
        criteria.andIsDeleteEqualTo(GameConstants.IS_NOT_DELETE);
        List<TbGameEventTeam> list = gameEventTeamMapper.selectByExample(teamExample);
        if (CollectionUtils.isEmpty(list)) {
            respGameResult.setStatus(0);
        } else {
            respGameResult.setStatus(1);
        }
        return APIResponse.returnSuccess(respGameResult);
    }

    @Override
    public APIResponse<RespCheckUser> checkUser(ReqCheckUser request) {
        RespCheckUser respCheckUser = new RespCheckUser();
        RespUserInfoBase user = baseService.queryUserMsgByPhone(request.getPhoneNumber());
        if(null == user){
            respCheckUser.setFlag((byte) 0);
        }else{
            respCheckUser.setFlag((byte) 1);
            respCheckUser.setUserId(user.getUid());
            respCheckUser.setIconUrl(user.getIcon());
            respCheckUser.setUserName(user.getNickName());
            respCheckUser.setSex(user.getGender());
        }
        return APIResponse.returnSuccess(respCheckUser);
    }

    @Override
    public PageObj<List<RespRecentSignUser>> getRecentSignUser(ReqRecentSginUser request) {
        PageObj<List<RespRecentSignUser>> result = null;
        Integer pageNo = 1;
        Integer pageSize = 20;
        if (request != null) {
            pageNo = request.getPageNo() ;
            pageSize = request.getPageSize();
        }

        List<RespRecentSignUser> respRecentSignUsers = Lists.newArrayList();
        TbGameHelpSignExample example = new TbGameHelpSignExample();
        TbGameHelpSignExample.Criteria criteria = example.createCriteria();
        criteria.andUidEqualTo(request.getUid());
        Integer totalCount = gameHelpSignMapper.countByExample(example);
        example.setPage(new Page((pageNo  ) * pageSize, pageSize, totalCount));
        example.setOrderByClause("sign_time DESC");
        List<TbGameHelpSign> list = gameHelpSignMapper.selectByExample(example);

        if(list.size() > 0){
            for(TbGameHelpSign helpSign : list){

                //查询用户基本信息
                RespUserInfoDetail userInfoDetail = baseService.queryUserMsg(helpSign.getHelpSignUid());
                if(userInfoDetail == null){
                    continue;
                }
                RespRecentSignUser respRecentSignUser = new RespRecentSignUser();
                respRecentSignUser.setIconUrl(userInfoDetail.getIcon());
                respRecentSignUser.setUserId(userInfoDetail.getUid());
                respRecentSignUser.setUserName(userInfoDetail.getNickName());
                respRecentSignUser.setSex(userInfoDetail.getGender());
                respRecentSignUser.setSignCount(getUserSignCount(userInfoDetail.getUid()));
                TbGameEventTeamExample example1 = new TbGameEventTeamExample();
                TbGameEventTeamExample.Criteria criteria1 = example1.createCriteria();
                criteria1.andGameEventIdEqualTo(request.getGameId());
                criteria1.andUidEqualTo(helpSign.getHelpSignUid());
                List<TbGameEventTeam> teams = gameEventTeamMapper.selectByExample(example1);
                if(teams.size() == 1){
                    respRecentSignUser.setIsSigned(1);
                }
                //查询用户俱乐部成员信息
                try {
                    RespIsClubMember respIsClubMember = clubOpenService.isClubMember(request.getClubId(), helpSign.getHelpSignUid());
                    if (respIsClubMember.isFlag()) {
                        switch (respIsClubMember.getRoleCode()) {
                            case "ROLE_CLUB_PRESIDENT":
                                respRecentSignUser.setClubMemberMsg("主席");
                                break;
                            case "ROLE_CLUB_FINANCIAL":
                                respRecentSignUser.setClubMemberMsg("财务管理员");
                                break;
                            case "ROLE_CLUB_ADMIN":
                                respRecentSignUser.setClubMemberMsg("管理员");
                                break;
                            case "ROLE_CLUB_MEMBER":
                                respRecentSignUser.setClubMemberMsg("");
                                break;
                            default:
                                respRecentSignUser.setClubMemberMsg("");
                                break;
                        }
                    }
                }catch (Exception e){
                    logger.info("查询用户俱乐部信息失败！");
                }
                respRecentSignUsers.add(respRecentSignUser);
            }
            result = PageObj.create(totalCount, pageNo, pageSize, respRecentSignUsers);
            return result;
        }else{
            return result;
        }
    }

    @Override
    public APIResponse<PageObj<List<RespRecentSignUser>>> helpSign(ReqRecentSginUser request) {
        //返回已经报名用户和最近报名成员
        PageObj<List<RespRecentSignUser>> recentUser = null;
        List<Integer> signUser = null;
        if(request.getGameId() != 0) {
            TbGameEvent tbGameEvent = gameEventMapper.selectByPrimaryKey(request.getGameId());
            if (null == tbGameEvent) {
                logger.info("用户uid={}，以俱乐部id={}开始报名活动gameid={}报名失败，原因：{}", request.getUid(), request.getClubId(), request.getGameId(), GameSignUpEnum.HAVING_NOT_GAME_FROM_GAMEID.getLabel());
                return APIResponse.returnFail(GameSignUpEnum.HAVING_NOT_GAME_FROM_GAMEID.getId(), GameSignUpEnum.HAVING_NOT_GAME_FROM_GAMEID.getName());
            }
//            if (new Date().after(tbGameEvent.getEndTime())) {
//                logger.info("用户uid={}，以俱乐部id={}开始报名活动gameid={}报名失败，原因：{}", request.getUid(), request.getClubId(), request.getGameId(), GameSignUpEnum.GAME_IS_END_STOP_SIGN.getLabel());
//                return APIResponse.returnFail(GameSignUpEnum.GAME_IS_END_STOP_SIGN.getId(), GameSignUpEnum.GAME_IS_END_STOP_SIGN.getName());
//            }
//            if (new Date().after(tbGameEvent.getSignEndTime())) {
//                logger.info("用户uid={}，以俱乐部id={}开始报名活动gameid={}报名失败，原因：{}", request.getUid(), request.getClubId(), request.getGameId(), GameSignUpEnum.GAME_SIGN_IS_SOPT.getLabel());
//                return APIResponse.returnFail(GameSignUpEnum.GAME_SIGN_IS_SOPT.getId(), GameSignUpEnum.GAME_SIGN_IS_SOPT.getName());
//            }

            //轮次没有生成就可以代报名
            if(tbGameEvent.getCurrentRoundId() > 0){
                logger.error("轮次已经生成，不能继续报名");
                return APIResponse.returnFail("轮次已经生成，不能继续报名");
            }

            if (tbGameEvent.getInventoryLevel() <= 0) {
                logger.info("用户uid={}，以俱乐部id={}开始报名活动gameid={}报名失败，原因：{}", request.getUid(), request.getClubId(), request.getGameId(), GameSignUpEnum.GAME_SIGN_USER_IS_FULL.getLabel());
                return APIResponse.returnFail(GameSignUpEnum.GAME_SIGN_USER_IS_FULL.getId(), GameSignUpEnum.GAME_SIGN_USER_IS_FULL.getName());
            }
            if(tbGameEvent.getIsVisible() == 1){
                //对外比赛，要查询最近报名成员
                recentUser =  getRecentSignUser(request);
            }
        }else{
            recentUser =  getRecentSignUser(request);
        }
        //查询报名用户
        {
            TbGameEventTeamExample teamExample = new TbGameEventTeamExample();
            TbGameEventTeamExample.Criteria criteria = teamExample.createCriteria();
            criteria.andGameEventIdEqualTo(request.getGameId());
            criteria.andIsDeleteEqualTo(GameConstants.IS_NOT_DELETE);
            List<TbGameEventTeam> teams = gameEventTeamMapper.selectByExample(teamExample);
            for(TbGameEventTeam tbGameEventTeam : teams){
                signUser = Lists.newArrayList();
                signUser.add(tbGameEventTeam.getUid());
            }
        }

        RespHelpSign respHelpSign = new RespHelpSign();
        respHelpSign.setRecentUser(recentUser);
        respHelpSign.setSignUser(signUser);
        officialGameCache.delGameEvent(request.getGameId());
        return APIResponse.returnSuccess(recentUser);
    }

    @Override
    public APIResponse<List<RespRecentSignUser>> getClubUser(ReqRecentSginUser request) {
        List<RespRecentSignUser> respRecentSignUsers = Lists.newArrayList();
        if(StringUtils.isEmpty(request.getKeyWord())){
            request.setKeyWord("");
        }
        List<RespClubMember> list = clubOpenService.searchClubMember(request.getClubId(),request.getKeyWord());
        if(list == null || list.size() == 0){
            return APIResponse.returnSuccess();
        }
        for(RespClubMember respClubMember : list){
            RespRecentSignUser respRecentSignUser = new RespRecentSignUser();
            respRecentSignUser.setUserName(respClubMember.getUsername());
            respRecentSignUser.setUserId(respClubMember.getUid());
            respRecentSignUser.setIconUrl(respClubMember.getAvatar());
            respRecentSignUser.setSex(respClubMember.getGender());
            respRecentSignUser.setSignCount(getUserSignCount(respClubMember.getUid()));
            respRecentSignUser.setClubMemberMsg("");
            if (null != respClubMember.getRoleCode()) {
                switch (respClubMember.getRoleCode()){
                    case "ROLE_CLUB_PRESIDENT" : respRecentSignUser.setClubMemberMsg("主席");break;
                    case "ROLE_CLUB_FINANCIAL" : respRecentSignUser.setClubMemberMsg("财务管理员");break;
                    case "ROLE_CLUB_ADMIN" : respRecentSignUser.setClubMemberMsg("管理员");break;
                    case "ROLE_CLUB_MEMBER" : respRecentSignUser.setClubMemberMsg("");break;
                    default:respRecentSignUser.setClubMemberMsg("");break;
                }
            }
            respRecentSignUser.setIsSigned(checkUserHasSign(request.getGameId(),respClubMember.getUid()));
            respRecentSignUsers.add(respRecentSignUser);
        }
        return APIResponse.returnSuccess(respRecentSignUsers);
    }

    @Override
    public APIResponse<RespRecentSignUser> getUserMsg(ReqUserMsg request) {
        RespUserInfoBase respUserInfoBase = baseService.queryUserMsgByPhone(request.getMobile());
        if(respUserInfoBase != null){
            RespRecentSignUser respRecentSignUser = new RespRecentSignUser();
            respRecentSignUser.setIsSigned(checkUserHasSign(request.getGameId(),respUserInfoBase.getUid()));
            respRecentSignUser.setSignCount(getUserSignCount(respUserInfoBase.getUid()));
            respRecentSignUser.setSex(respUserInfoBase.getGender());
            respRecentSignUser.setUserId(respUserInfoBase.getUid());
            respRecentSignUser.setIconUrl(respUserInfoBase.getIcon());
            respRecentSignUser.setUserName(respUserInfoBase.getNickName());
            return APIResponse.returnSuccess(respRecentSignUser);
        }else{
            return APIResponse.returnSuccess();
        }
    }

    @Override
    public APIResponse<RespRecentSignUser> getClubUserMsg(ReqClubUser request) {

        List<RespRecentSignUser> list1 = Lists.newArrayList();
        List<RespClubMemberBaseInfo> list = clubOpenService.getClubMembers(request.getClubId(),false);
        if(list.size() > 0){
            for(RespClubMemberBaseInfo respClubMemberBaseInfo : list){
                RespUserInfoDetail respUserInfoDetail = baseService.queryUserMsg(respClubMemberBaseInfo.getUid());
                RespRecentSignUser respRecentSignUser = new RespRecentSignUser();
                respRecentSignUser.setUserId(respUserInfoDetail.getUid());
                respRecentSignUser.setUserName(respUserInfoDetail.getNickName());
                respRecentSignUser.setSex(respUserInfoDetail.getGender());
                respRecentSignUser.setIconUrl(respUserInfoDetail.getIcon());
                respRecentSignUser.setSignCount(getUserSignCount(respUserInfoDetail.getUid()));
                respRecentSignUser.setIsSigned(checkUserHasSign(request.getGameId(),respUserInfoDetail.getUid()));

                RespIsClubMember respIsClubMember = clubOpenService.isClubMember(request.getClubId(),respUserInfoDetail.getUid());
                if(respIsClubMember.isFlag()){
                    switch (respIsClubMember.getRoleCode()){
                        case "ROLE_CLUB_PRESIDENT" : respRecentSignUser.setClubMemberMsg("主席");break;
                        case "ROLE_CLUB_FINANCIAL" : respRecentSignUser.setClubMemberMsg("财务管理员");break;
                        case "ROLE_CLUB_ADMIN" : respRecentSignUser.setClubMemberMsg("管理员");break;
                        case "ROLE_CLUB_MEMBER" : respRecentSignUser.setClubMemberMsg("");break;
                        default:respRecentSignUser.setClubMemberMsg("");break;
                    }
                }

            }
        }
        return APIResponse.returnSuccess();
    }

    @Override
    public APIResponse insertTeam(int gameId, List<List<Integer>> uids,int isDouble) {
        TbGameEvent gameEvent = gameEventMapper.selectByPrimaryKey(gameId);
        if(null != gameEvent){
            if(isDouble == 0) {
                TbGameEventTeamExample teamExample = new TbGameEventTeamExample();
                TbGameEventTeamExample.Criteria criteria = teamExample.createCriteria();
                criteria.andGameEventIdEqualTo(gameId);
                criteria.andUidIn(uids.get(0));
                List<TbGameEventTeam> list = gameEventTeamMapper.selectByExample(teamExample);
                if (list.size() > 0) {
                    return APIResponse.returnFail("插入失败");
                } else {
                    for (List<Integer> uid : uids) {
                        TbGameEventTeam tbGameEventTeam = new TbGameEventTeam();
                        tbGameEventTeam.setUid(uid.get(0));
                        tbGameEventTeam.setGameEventId(gameId);
                        gameEventTeamMapper.insertSelective(tbGameEventTeam);
                    }
                }
            }else{
                for(List<Integer> list : uids) {
                    insertDoubleTeam(gameEvent, list, null);
                }
            }
            gameEvent.setInventoryLevel(0);
            gameEventMapper.updateByPrimaryKeySelective(gameEvent);
            return APIResponse.returnSuccess();
        }else{
            return APIResponse.returnFail("赛事不存在");
        }
    }

    @Override
    public void updateDoubleTeam(int gameEventId, List<List<Integer>> uids) {
        List<TbGameEventTeam> list = gameSystemDao.selectTbGameEventTeamByGameEventId(gameEventId, GameConstants.IS_NOT_DELETE);
        if (CollectionUtils.isNotEmpty(list)) {
            Map<Integer, Integer> param= new HashMap<>();
            for (TbGameEventTeam team : list) {
                param.put(team.getUid(), team.getId());
            }
            bizGameOrderDao.delTbTeamDoubleAddendum(gameEventId);
            logger.info("当前赛事id:{}, 用户对应队伍集合:{}", gameEventId, param);
            for (List<Integer> temp : uids) {
                List<Integer> eventTeamIds = new ArrayList<>();
                for (Integer inte : temp) {
                    eventTeamIds.add(param.get(inte));
                }
                bizGameOrderDao.insertTbTeamDoubleAddendum(gameEventId, eventTeamIds);
            }
        }
    }


    /**
     * 更新代报名信息表
     * @param uid
     * @param uids
     */
    public void updateTbRecentUser(Integer uid,List<Integer> uids){
        for(Integer id : uids){
            TbGameHelpSignExample helpSignExample = new TbGameHelpSignExample();
            TbGameHelpSignExample.Criteria criteria = helpSignExample.createCriteria();
            criteria.andUidEqualTo(uid);
            criteria.andHelpSignUidEqualTo(id);
            criteria.andIsDeleteEqualTo(GameConstants.IS_NOT_DELETE);
            List<TbGameHelpSign> helpSigns = gameHelpSignMapper.selectByExample(helpSignExample);
            if(helpSigns.size() == 0){
                TbGameHelpSign tbGameHelpSign = new TbGameHelpSign();
                tbGameHelpSign.setUid(uid);
                tbGameHelpSign.setHelpSignUid(id);
                tbGameHelpSign.setSignTime(new Date());
                tbGameHelpSign.setIsDelete(GameConstants.IS_NOT_DELETE);
                gameHelpSignMapper.insertSelective(tbGameHelpSign);
            }else{
                TbGameHelpSign tbGameHelpSign = new TbGameHelpSign();
                tbGameHelpSign.setSignTime(new Date());
                tbGameHelpSign.setId(helpSigns.get(0).getId());
                gameHelpSignMapper.updateByPrimaryKeySelective(tbGameHelpSign);
            }
        }
    }

    /**
     * 更新用户报名活动的数量
     * @param uids
     * @param type
     */
    public void updateUserSignCount(List<Integer> uids,int type) {
        for (Integer uid : uids) {
            TbUserSignCountExample tbUserSignCountExample = new TbUserSignCountExample();
            TbUserSignCountExample.Criteria criteria = tbUserSignCountExample.createCriteria();
            criteria.andTypeEqualTo(type);
            criteria.andUidEqualTo(uid);
            List<TbUserSignCount> tbUserSignCounts = userSignCountMapper.selectByExample(tbUserSignCountExample);
            TbUserSignCount tbUserSignCount = new TbUserSignCount();
            if(tbUserSignCounts.size() == 0){
                tbUserSignCount.setUid(uid);
                tbUserSignCount.setType(type);
                tbUserSignCount.setCount(1);
                userSignCountMapper.insertSelective(tbUserSignCount);
            }else{
                tbUserSignCount.setId(tbUserSignCounts.get(0).getId());
                tbUserSignCount.setCount(tbUserSignCounts.get(0).getCount() + 1);
                userSignCountMapper.updateByPrimaryKeySelective(tbUserSignCount);
            }
        }
    }

    private int checkUserHasSign(int gameId,int uid){
        TbGameEventTeamExample tbGameEventTeamExample = new TbGameEventTeamExample();
        TbGameEventTeamExample.Criteria criteria = tbGameEventTeamExample.createCriteria();
        criteria.andGameEventIdEqualTo(gameId);
        criteria.andUidEqualTo(uid);
        criteria.andIsDeleteEqualTo(GameConstants.IS_NOT_DELETE);
        List<TbGameEventTeam> teams = gameEventTeamMapper.selectByExample(tbGameEventTeamExample);
        return teams.size() == 0 ? 0 :1;
    }

    /**
     * 查询用户参加活动次数
     * @param uid
     */
    private int getUserSignCount(int uid){
        TbUserSignCountExample tbUserSignCountExample = new TbUserSignCountExample();
        TbUserSignCountExample.Criteria criteria = tbUserSignCountExample.createCriteria();
        criteria.andUidEqualTo(uid);
        List<TbUserSignCount> list = userSignCountMapper.selectByExample(tbUserSignCountExample);
        if(list.size() == 0){
            return 0;
        }else {
            int count = 0;
            for (TbUserSignCount userSignCount : list) {
                count += userSignCount.getCount();
            }
            return count;
        }
    }
}
